// 公用方法

// 事件总线
import Vue from 'vue'
export const EventBus = new Vue()

// 时间戳转换
export function formatDate(value) {
  let date = new Date(value);
  let y = date.getFullYear();
  let MM = date.getMonth() + 1;
  MM = MM < 10 ? ('0' + MM) : MM;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  let h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  let m = date.getMinutes();
  m = m < 10 ? ('0' + m) : m;
  let s = date.getSeconds();
  s = s < 10 ? ('0' + s) : s;
  return y + '年' + MM + '月' + d + ' 日 ' + h + ':' + m + ':' + s;
}

// 发布时间转换
export function releaseTime(value) {
  let date = new Date();
  let valueDate = formatDate(value);
  let year = date.getFullYear();
  let mouth = date.getMonth() + 1;
  let today = date.getDate();
  if (
    valueDate.slice(0, 4) == year &&
    valueDate.slice(5, 7) == mouth &&
    valueDate.slice(8, 10) == today
  ) {
    return valueDate.slice(10, 16);
  }
  if (
    Number(valueDate.slice(8, 10)) + 1 == today &&
    valueDate.slice(0, 4) == year &&
    valueDate.slice(5, 7) == mouth
  ) {
    return `昨天${valueDate.slice(10, 16)}`;
  }
  if (valueDate.slice(0, 4) == year) {
    return valueDate.slice(5, 10) + '日';
  }
  return valueDate.slice(0, 10) + '日';
}

// 音乐时长转换
export function formatTime(time) {
  if (time === 0) {
    return '00:00'
  }
  const mins = Math.floor(time / 60) < 10 ? `0${Math.floor(time / 60)}` : Math.floor(time / 60)
  const sec = Math.floor(time % 60) < 10 ? `0${Math.floor(time % 60)}` : Math.floor(time % 60)
  return `${mins}:${sec}`
}

// 防抖&节流
export const debounce = (fn, t) => {
  let delay = t || 500;
  let times = null;
  if (times) {
    clearTimeout(times)
  } else {
    times = setTimeout(() => {
      fn();
    }, delay)
  }
}

// 判断是否已登录
export function judgeLogin(_this) {
  if (!_this.$store.state.userInfo.cookie) {
    _this.globalObj.$Dialog.confirm({
      message: '未登录，是否前往登录?',
    }).then(() => {
      _this.$router.push('/login');
    }).catch(() => {
      _this.$router.go(-1)
    });
    return false
  } else {
    return true
  }
}